#include <bits/stdc++.h>

using namespace std;

struct TreeNode
{
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};

class Solution
{
public:
    vector<int> traverse(TreeNode *root)
    {
        vector<int> res;
        if (root == nullptr)
        {
            return res;
        }
        queue<TreeNode *> que;
        que.push(root);
        while (!que.empty())
        {
            int size = que.size();
            for (int i = 0; i < size; i++)
            {
                TreeNode *cur = que.front();
                que.pop();
                res.push_back(cur->val);
                if (cur->left)
                {
                    que.push(cur->left);
                }
                if (cur->right)
                {
                    que.push(cur->right);
                }
            }
        }
        return res;
    }

    TreeNode *recursion(vector<int> &nums, int start, int end)
    {
        if (end - start == 0)
        {
            return nullptr;
        }
        int max = nums[start];
        int index = start;
        for (int i = start; i < end; i++)
        {
            if (nums[i] > max)
            {
                index = i;
                max = nums[i];
            }
        }
        TreeNode *root = new TreeNode(max);
        if (end - start == 1)
        {
            return root;
        }

        int left_start = start;
        int left_end = index;

        int right_start = index + 1;
        int right_end = end;

        root->left = recursion(nums, left_start, left_end);
        root->right = recursion(nums, right_start, right_end);

        return root;
    }

    TreeNode *constructMaximumBinaryTree(vector<int> &nums)
    {
        if (nums.size() == 0)
        {
            return nullptr;
        }
        return recursion(nums, 0, nums.size());
    }
};

int main()
{
    vector<int> vec{3, 2, 1, 6, 0, 5};
    Solution sol;
    TreeNode *root = sol.constructMaximumBinaryTree(vec);
    vector<int> res = sol.traverse(root);
    for (auto num : res)
    {
        cout << num << " ";
    }
    cout << endl;
    return 0;
}